package com.example.sulingorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sulingorder.conster.RedisConster;
import com.example.sulingorder.dao.OrderDao;
import com.example.sulingorder.entity.*;
import com.example.sulingorder.feign.ProductFeign;
import com.example.sulingorder.feign.UserFeign;
import com.example.sulingorder.feign.WalletFeign;
import com.example.sulingorder.service.*;
import com.example.sulingorder.utils.MyUtils;
import com.example.sulingorder.vo.*;
import com.xiao.sulingpublic.to.BusinessTo;
import com.xiao.sulingpublic.to.CommodityTo;
import com.xiao.sulingpublic.to.MemberAddressTo;
import com.xiao.sulingpublic.utils.PageUtils;
import com.xiao.sulingpublic.utils.Query;
import com.xiao.sulingpublic.utils.R;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author 13221
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderReleaseinfoService orderReleaseinfoService;

    @Autowired
    private OrderEarthService orderEarthService;

    @Autowired
    private OrderCommodityService orderCommodityService;

    @Autowired
    private OrderClassifyService orderClassifyService;

    @Autowired
    private RedisUtilsService redisUtilsService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private WalletFeign walletFeign;

    /**
     * 多线程
     */
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        System.out.println(params);
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 处理 用户发布的帮领 订单
     *
     * @param releaseOrderVo     :提交的数据,订单相关信息
     * @param releaseOrderInfoVo :领取需要的信息
     * @param orderEarthEntity   :完整的地址信息
     * @return :返回订单号
     * @Transactional 开启事务
     */
    @Transactional
    @Override
    public String saveOrder(ReleaseOrderVo releaseOrderVo, ReleaseOrderInfoVo releaseOrderInfoVo, OrderEarthEntity orderEarthEntity, String formCode) throws Exception {

        //hint 验证接口防刷code
        String key = RedisConster.FORM_CODE_KEY + releaseOrderVo.getOrMemberId();
        boolean b = redisUtilsService.testRedisFormCode(key, formCode);
        if (!b) {
            //验证不通过
            throw new Exception();
        }

        /*
         * 1.创建订单id
         * 2.将订单id放到过期队列
         * 3.保存数据到redis中
         * 4.保存数据
         */
        //hint 创建订单号  uuid+用户号
        String orderSeq = MyUtils.getOrderSeq();
        String orderSn = releaseOrderVo.getOrMemberId() + ":" + orderSeq;
        //hint 将订单号token放到过期消息队列中
        /*
         参数一:交换机名
         参数二:路由键
         参数三:数据
         */
        rabbitTemplate.convertAndSend("suling.exchange", "suling.exchange.key", orderSn);

        //hint 构建数据
        OrderEntity orderEntity = new OrderEntity();
        //订单号
        orderEntity.setOrOrderSn(orderSeq);
        //发布订单的用户号
        orderEntity.setOrMemberId(releaseOrderVo.getOrMemberId());
        //订单总价
        orderEntity.setOrOrderTotalPrice(releaseOrderVo.getOrOrderTotalPrice());
        //订单所属分类
        orderEntity.setOrOrderClassifyId(releaseOrderVo.getOrOrderClassifyId());
        //订单状态
        orderEntity.setOrOrderState(0);
        //创建时间
        orderEntity.setOrCreateDate(new Date());


        //hint 保存领取需要的信息
        OrderReleaseinfoEntity orderReleaseinfoEntity = new OrderReleaseinfoEntity();
        orderReleaseinfoEntity.setOorOrderSn(Long.valueOf(orderSeq));
        orderReleaseinfoEntity.setOorName(releaseOrderInfoVo.getName());
        orderReleaseinfoEntity.setOorMobile(String.valueOf(releaseOrderInfoVo.getMobile()));
        orderReleaseinfoEntity.setOorReceiveCode(releaseOrderInfoVo.getReceiveCode());
        orderReleaseinfoEntity.setOorOrderState(0);
        orderReleaseinfoEntity.setOorRemark(releaseOrderInfoVo.getRemark());

        //hint 保存起始地, 目的地
//        OrderEarthEntity orderEarthEntity = new OrderEarthEntity();
//        orderEarthEntity.setOoeOrderSn(orderSeq);
//
//        orderEarthEntity.setOoeOrderBegin(releaseOrderVo.getOoeOrderBegin());
//        orderEarthEntity.setOoeOrderEnd(releaseOrderVo.getOoeOrderEnd());
        orderEarthEntity.setOoeOrderSn(orderSeq);

        //hint 保存数据到redis中
        HelpRedisDataVo helpRedisDataVo = new HelpRedisDataVo();
        BeanUtils.copyProperties(orderEntity, helpRedisDataVo);
        helpRedisDataVo.setOrderEarthEntity(orderEarthEntity);
        String s = JSON.toJSONString(helpRedisDataVo);
        redisTemplate.opsForValue().set(RedisConster.NOPAY_ORDER_KEY + orderSn, s, 24, TimeUnit.HOURS);
        //将订单号对应的用户号保存进redis中, 支付成功后的处理函数需要用
        redisTemplate.opsForValue().set(RedisConster.USERNAME_ORDER_KEY + orderSeq, releaseOrderVo.getOrMemberId(), 24, TimeUnit.HOURS);
//        redisTemplate.opsForValue().set(RedisConster.ORDER_KEY + orderSn, s, 24, TimeUnit.HOURS);

        //hint 保存数据
        boolean save = orderService.save(orderEntity);
        boolean save1 = orderReleaseinfoService.save(orderReleaseinfoEntity);
        boolean save2 = orderEarthService.save(orderEarthEntity);

        if (!save && !save1 && !save2) {
            throw new Exception();
        }

        return orderSeq;
    }

    /**
     * 处理 用户发布的帮买 订单
     *
     * @param helpFormDataVo :提交的数据,订单相关信息
     * @return :返回订单号
     * @Transactional 开启事务
     */
    @Transactional
    @Override
    public R saveHelpBuyOrder(HelpFormDataVo helpFormDataVo) throws Exception {
        //hint 验证接口防刷code
        String key = RedisConster.FORM_CODE_KEY + helpFormDataVo.getOrMemberId();
        boolean b = redisUtilsService.testRedisFormCode(key, helpFormDataVo.getFormCode());
        if (!b) {
            //验证不通过
            return R.error("验证不通过");
        }

        CompletableFuture.runAsync(() -> {
            //hint 判断是否要保存地址, 是的说远程保存一下
            if (null != helpFormDataVo.getOrderEarthEntity() && helpFormDataVo.isSaveAddress()) {
                MemberAddressTo memberAddressTo = new MemberAddressTo();
                OrderEarthEntity orderEarthEntity = helpFormDataVo.getOrderEarthEntity();

                BeanUtils.copyProperties(orderEarthEntity, memberAddressTo);

                String ooeOrderEnd = orderEarthEntity.getOoeOrderEnd();
                String[] s = ooeOrderEnd.split(" ");
                // 地址
                memberAddressTo.setMaAddress(s[0]);
                // 详细地址
                memberAddressTo.setMaAddressDetailed(s[1]);
                // 联系电话
                memberAddressTo.setMaConnectMobile(s[2]);
                // 联系昵称
                memberAddressTo.setMaConnectName(s[3]);
                // 用户号
                memberAddressTo.setMaUsername(helpFormDataVo.getOrMemberId());


                //调用远程保存地址信息
                userFeign.saveAddress(memberAddressTo);
            }
        }, executor);


        //验证通过,保存订单数据
        /*
         * 0.异步保存收货地址
         * 1.创建订单id
         * 2.将订单id放到过期队列
         * 3.保存数据到redis中
         * 4.保存数据
         */
        //hint 创建订单号
        String orderSeq = MyUtils.getOrderSeq();
        //hint 用户号+uuid 商品数据在redis中的key
        String orderSn = helpFormDataVo.getOrMemberId() + ":" + orderSeq;
        //hint 将订单号token放到过期消息队列中
        /*
         参数一:交换机名
         参数二:路由键
         参数三:数据
         */
        rabbitTemplate.convertAndSend("suling.exchange", "suling.exchange.key", orderSn);

        //hint 保存订单涉及的商品数据
        List<Long> productId = new ArrayList<>();
        List<HelpFormDataVo.ShowProductData> showProductData = helpFormDataVo.getShowProductData();
        List<OrderCommodityEntity> collect = showProductData.stream().map(ite -> {
            HelpFormDataVo.Data data = ite.getData();

            OrderCommodityEntity orderCommodity = new OrderCommodityEntity();
            orderCommodity.setOrcOrderSn(orderSeq);
            orderCommodity.setOrcCommodityNum(ite.getNum());
            orderCommodity.setOrcCommodityPrice(data.getCoPrice());
            orderCommodity.setOrcCoId(data.getCoId());
            //商品购买的状态 0未购买 1 购买成功 -1购买失败
            orderCommodity.setOrcState(0);

            productId.add(data.getCoId());

            return orderCommodity;
        }).collect(Collectors.toList());

        //hint 异步获取要购买的商品信息, 主要构件商品价格数据,
        CompletableFuture<R> rComplet = CompletableFuture.supplyAsync(() -> productFeign.listByIds(productId), executor);


        //hint 保存收货地址
        OrderEarthEntity orderEarthEntity = helpFormDataVo.getOrderEarthEntity();
        orderEarthEntity.setOoeOrderSn(orderSeq);

        //hint 构建订单数据
        OrderEntity orderEntity = new OrderEntity();
        //订单号
        orderEntity.setOrOrderSn(orderSeq);
        //发布订单的用户号
        orderEntity.setOrMemberId(helpFormDataVo.getOrMemberId());
        //订单佣金
        orderEntity.setOrOrderTotalPrice(helpFormDataVo.getCommission());
        //订单所属分类
        orderEntity.setOrOrderClassifyId(1L);
        //店铺号
        orderEntity.setOrBuId(helpFormDataVo.getShopUsername());
        //订单状态
        orderEntity.setOrOrderState(0);
        //创建时间
        orderEntity.setOrCreateDate(new Date());

        //hint 保存数据到redis中, 保存所有前端发来的数据,因为后面还要显示,为了后续不过多查询  也要保存地址信息,
        //订单总价, 按商品id查询到所有商品价格,计算出总价,
        R r = rComplet.get();
        List<BigDecimal> prices = (List<BigDecimal>) r.get("prices");
        BigDecimal price = new BigDecimal("0.00");
        for (int i = 0; i < prices.size(); i++) {
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(prices.get(i)));
            price = bigDecimal.add(price);
        }
        BigDecimal add = price.add(helpFormDataVo.getCommission());
        orderEntity.setOrOrderTotalPrice(add);
        //保存在redis是中后面要显示用
        helpFormDataVo.setTotalPrice(add);
        helpFormDataVo.setOrderSn(orderSeq);

        String s = JSON.toJSONString(helpFormDataVo);
        redisTemplate.opsForValue().set(RedisConster.NOPAY_ORDER_KEY + orderSn, s, 24, TimeUnit.HOURS);
        //将订单号对应的用户号保存进redis中, 支付成功后的处理函数需要用
        redisTemplate.opsForValue().set(RedisConster.USERNAME_ORDER_KEY + orderSeq, helpFormDataVo.getOrMemberId() , 24, TimeUnit.HOURS);

        //hint 保存数据
        boolean save = orderService.save(orderEntity);
        boolean save1 = orderCommodityService.saveBatch(collect);
        boolean save2 = orderEarthService.save(orderEarthEntity);

        if (save && save1 && save2) {
            return R.ok().put("orderSn", orderSeq);
        } else {
            throw new Exception();
        }
    }

    /**
     * 获取订单全部信息, 注意帮领和帮买的区别,  (暂时无引用,就是没用)
     *
     * @param username: 发布者用户号
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public R getOrderList(String username) throws ExecutionException, InterruptedException {
        //hint 获取用户所有订单,注意订单包含过期状态
        List<OrderEntity> orderEntityList = orderService.list(new QueryWrapper<OrderEntity>().eq("or_member_id", username).orderByDesc("or_id"));

        if (orderEntityList != null) {
            List<OrderDataAllVo> list = new ArrayList<>();
            OrderDataAllVo orderDataAllVo = new OrderDataAllVo();

            for (OrderEntity orderEntity : orderEntityList) {
//                //1.查询订单所属分类名
//                CompletableFuture<OrderClassifyEntity> orderClassifyThread = CompletableFuture.supplyAsync(() -> orderClassifyService.getById(orderEntity.getOrOrderClassifyId()), executor);
//
//                //3.获取订单收货地址
//                CompletableFuture<OrderEarthEntity> orderEarth = CompletableFuture.supplyAsync(() -> orderEarthService.getOne(new QueryWrapper<OrderEarthEntity>().eq("ooe_order_sn", orderEntity.getOrOrderSn())), executor);
//
//                // hint 判断订单是帮领订单 还是帮买订单
//                if (orderEntity.getOrOrderClassifyId() == 1) {
//                    //2.获取订单涉及的对应商品集合
//                    CompletableFuture<List<OrderCommodityEntity>> orderCommodityList = CompletableFuture.supplyAsync(() -> {
//                        return orderCommodityService.list(new QueryWrapper<OrderCommodityEntity>().eq("orc_order_sn", orderEntity.getOrOrderSn()));
//                    }, executor);
//                    //2.1.远程 获取商品信息
//                    CompletableFuture<List<CommodityTo>> commodityTos1 = orderCommodityList.thenApplyAsync((ret) -> {
//                        List<Long> collect = ret.stream().map(ite -> {
//                            return ite.getOrcCoId();
//                        }).collect(Collectors.toList());
//                        R r = productFeign.getCommodityList(collect);
//                        List<CommodityTo> commodityTos = (List<CommodityTo>) r.get("commodityTos");
//                        return commodityTos;
//                    }, executor);
//
//                    //4.远程获取订单店铺信息
//                    CompletableFuture<Object> businessTo1 = CompletableFuture.supplyAsync(() -> {
//                        R r = productFeign.getBusiness(orderEntity.getOrBuId());
//                        return r.get("businessTo");
//                    }, executor);
//
//                    OrderClassifyEntity orderClassifyEntity = orderClassifyThread.get();
//                    List<OrderCommodityEntity> orderCommodityEntities = orderCommodityList.get();
//                    List<CommodityTo> commodityTos = commodityTos1.get();
//                    OrderEarthEntity orderEarthEntity = orderEarth.get();
//                    String shopAddress = (String) businessTo1.get();
//                    BusinessTo businessTo = JSON.parseObject(shopAddress, BusinessTo.class);
//
//                    //计算商品总价
//                    BigDecimal bigDecimal = new BigDecimal("0");
//                    for (OrderCommodityEntity orderCommodityEntity : orderCommodityEntities) {
//                        BigDecimal multiply = orderCommodityEntity.getOrcCommodityPrice().multiply(new BigDecimal(orderCommodityEntity.getOrcCommodityNum()));
//                        bigDecimal = bigDecimal.add(multiply);
//                    }
//                    //佣金
//                    bigDecimal = orderEntity.getOrOrderTotalPrice().subtract(bigDecimal);
//                    orderDataAllVo = new OrderDataAllVo(bigDecimal, orderEntity, orderClassifyEntity, orderCommodityEntities, commodityTos, orderEarthEntity, businessTo, null);
//
//                } else if (orderEntity.getOrOrderClassifyId() == 0) {
//                    //查询 OrderReleaseinfoController
//
//                    OrderReleaseinfoEntity orderReleaseinfo = orderReleaseinfoService.getOne(new QueryWrapper<OrderReleaseinfoEntity>().eq("oor_order_sn", orderEntity.getOrOrderSn()));
//
//                    OrderClassifyEntity orderClassifyEntity = orderClassifyThread.get();
//                    OrderEarthEntity orderEarthEntity = orderEarth.get();
//                    //帮领
//                    orderDataAllVo = new OrderDataAllVo(null, orderEntity, orderClassifyEntity, null, null, orderEarthEntity, null, orderReleaseinfo);
//                }


                list.add(getAll(orderEntity));
            }
            return R.ok().put("orderDataAllVoList", JSON.toJSONString(list));
        }

        return R.error("无订单数据");
    }


    /**
     * 获取订单数据,每次获取10个数据, 对应的订单详细信息
     * @param username :获取用户发布的订单数据
     * @param state :获取的订单类型
     * @param size  :当前数据起点
     * @return :订单数据
     */
    @Override
    public R getOrderListPagi(String username, Integer state, Integer size) throws ExecutionException, InterruptedException {
        //hint 获取用户所有订单,注意订单包含过期状态
        List<OrderEntity> orderEntityList = orderDao.getOrderListPagi(username, state, size, 10);

        if (orderEntityList != null) {
            List<OrderDataAllVo> list = new ArrayList<>();
            for (OrderEntity orderEntity : orderEntityList) {
                list.add(getAll(orderEntity));
            }
            return R.ok().put("orderDataAllVoList", JSON.toJSONString(list));
        }
        return R.error("无数据了");
    }


    /**
     * 发布者 确认收货, 扫码后发送数据过来
     * @param memberId :发布者号
     * @param userName :领取者号
     * @param orderSn  :要收货的订单号
     * @param code     :生成二维码时的code
     * @return :返回状态
     */
    @Transactional
    @Override
    public R haveReceipt(String memberId, String userName, String orderSn, String code) throws Exception {

        synchronized (this){
            //验证code
            String key = RedisConster.QR_CODE_KEY + userName + "-" + orderSn;
            String s = redisTemplate.opsForValue().get(key);
            if(!StringUtils.isEmpty(s)){
                //获取当前时间 - 生成code的时间 = 有没有过期
                String[] split = s.split("-");
                //2.验证code是否相等
                if(code.equals(split[0])){
                    //3.TODO 修改订单状态, 订单是
                    QueryWrapper<OrderEntity> wrapper = new QueryWrapper<OrderEntity>().eq("or_order_sn", orderSn).eq("or_member_id",memberId).eq("or_recipient_id",userName).in("or_order_state",1,2);
                    OrderEntity orderEntity = new OrderEntity();
                    OrderEntity one = this.getOne(wrapper);

                    //订单状态
                    orderEntity.setOrOrderState(4);
                    boolean update = this.update(orderEntity, wrapper);
                    if(update){
                        //4.TODO 将订单号放到消息队列中  监听消息队列,订单资金分配  可能有的商品购买失败
                        //修改钱包数据,判断订单帮领 ,将佣金 全部转到 领取人号中
                        //如果是帮领,将商品总价计算一下,将钱转到店铺号中, 将剩余佣金转到领取人号中
                        if(one.getOrOrderClassifyId() == 0){
                            //帮领
                            R r = walletFeign.updateAmount("1322127758", one.getOrRecipientId(), one.getOrOrderTotalPrice());
                            if(r == null){
                                throw new Exception();
                            }
                        }else if(one.getOrOrderClassifyId() == 1){
                            //帮买
                            //1.获取订单设计的商品
                            List<OrderCommodityEntity> orderCommoditys = orderCommodityService.list(new QueryWrapper<OrderCommodityEntity>().eq("orc_order_sn", orderSn));
                            //循环计算价格
                            BigDecimal bigDecimal = new BigDecimal("0");
                            for (OrderCommodityEntity orderCommodity : orderCommoditys) {
                                bigDecimal = bigDecimal.add(orderCommodity.getOrcCommodityPrice());
                            }
                            //默认从1322127758号将钱转出 转到店铺号
                            R r = walletFeign.updateAmount("1322127758", one.getOrBuId(),bigDecimal);
                            if(r == null){
                                throw new Exception();
                            }
                            //将钱转入 领取人号
                            r = walletFeign.updateAmount("1322127758", one.getOrRecipientId(), one.getOrOrderTotalPrice().subtract(bigDecimal));
                            if(r == null){
                                throw new Exception();
                            }
                        }


                        //5.TODO 保存订单收货状态进入redis中, 订单收货状态保留72小时,让处理
                        redisTemplate.opsForValue().set(RedisConster.RE_STATE_KEY + userName + "-" + orderSn, "1",72,TimeUnit.HOURS);

                        //6.删除code
                        redisTemplate.delete(key);

                        return R.ok();
                    }else{
                        return R.error("你可能不是收货人");
                    }
                }else {
                    return R.error("code验证失败,请重新扫码");
                }
            }

            return R.error("redis中该订单无数据");
        }
    }


    /**
     * 作用: 用户领取订单
     *
     * @param orderSn:   要领取的订单号
     * @param orMemberId:发布订单的用户号
     * @param username:领取人的用户号
     * @return 返回领取的订单号
     */
    @Transactional
    @Override
    public R upDataReceiveOrder(String orderSn, String orMemberId, String username, String formCode) {
        //验证code
        //hint 验证接口防刷code
        String key = RedisConster.FORM_CODE_KEY + username;
        boolean b = redisUtilsService.testRedisFormCode(key, formCode);
        if(b){
            //锁
            synchronized (this) {
                //TODO 1.先验证数据

                //验证订单是否已被领取,从数据库中查询
                OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("or_order_sn", orderSn));
                //判断订单类型为代领才能领
                if (null != orderEntity && orderEntity.getOrOrderState() == 0) {
                    OrderEntity orderEntity1 = new OrderEntity();
                    //2.修改状态
                    orderEntity1.setOrOrderState(1);
                    orderEntity1.setOrRecipientId(username);
                    this.update(orderEntity1, new QueryWrapper<OrderEntity>().eq("or_order_sn", orderSn));

                    //删除redis中的订单数据
                    Boolean delete = redisTemplate.delete(RedisConster.ORDER_KEY + orMemberId + ":" + orderSn);
                    if (null != delete && delete) {
                        return R.ok().put("orderSn", orderSn);
                    }
                }
                return R.error("订单已被领取");
            }
        }
        return R.error("防刷code验证不通过");
    }

    /**
     * 获取用户领取的订单信息, 获取用户领取的全部订单数据, 可查全部,可查指定订单
     * @param orderSn:  要获取的订单号数据
     * @param username: 要查询哪个用户的订单
     * @param sendUsername: 发布订单的用户号 不一定存在, 存在就是查询指定订单
     * @param orOrderState: 要查询的订单状态, 不一定存在, 存在就是查询指定状态
     */
    @Override
    public R getReceiveOrderData(String orderSn, String username, String sendUsername, Integer orOrderState) throws ExecutionException, InterruptedException {
        //1.构建查询条件
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        //如果orderSn不为null那么就是查询指定订单
        if(!StringUtils.isEmpty(orderSn)){
            //查询指定订单号
            wrapper.eq("or_order_sn",orderSn);
        }
        if(!StringUtils.isEmpty(sendUsername)){
            //查询指定发布人
            wrapper.eq("or_member_id",sendUsername);
        }
        //要查询的状态为 null,查询全部,但是排除未领状态
        if(null != orOrderState){
            wrapper.eq("or_order_state",orOrderState);
        }else{
            wrapper.ne("or_order_state",0);
        }
        //不管怎么样都要查询指定领取的用户号
        wrapper.eq("or_recipient_id",username);
        //2.获取订单数据
        List<OrderDataAllVo> orderDataAllVos = new ArrayList<>();
        //按条件查询
        List<OrderEntity> orderEntities = this.list(wrapper);

        for (OrderEntity orderEntity : orderEntities) {
            OrderDataAllVo orderDataAllVo = getAll(orderEntity);
            //5.获取订单 保存的领取信息
            OrderReleaseinfoEntity orderReleaseinfo = orderReleaseinfoService.getOne(new QueryWrapper<OrderReleaseinfoEntity>().eq("oor_order_sn", orderSn));
            //6.获取订单的领取需要的信息
            orderDataAllVo.setOrderReleaseinfoEntity(orderReleaseinfo);

            orderDataAllVos.add(orderDataAllVo);
        }

        return R.ok().put("orderDataAllVos",orderDataAllVos);
    }


    /**
     * 通过订单 OrderEntity 获取全部的 hint 相关信息
     */
    public OrderDataAllVo getAll(OrderEntity orderEntity) throws ExecutionException, InterruptedException {
        if (orderEntity != null) {
            OrderDataAllVo orderDataAllVo = new OrderDataAllVo();

            //1.查询订单所属分类名
            CompletableFuture<OrderClassifyEntity> orderClassifyThread = CompletableFuture.supplyAsync(() -> orderClassifyService.getById(orderEntity.getOrOrderClassifyId()), executor);

            //3.获取订单收货地址
            CompletableFuture<OrderEarthEntity> orderEarth = CompletableFuture.supplyAsync(() -> orderEarthService.getOne(new QueryWrapper<OrderEarthEntity>().eq("ooe_order_sn", orderEntity.getOrOrderSn())), executor);

            // hint 判断订单是帮领订单 还是帮买订单
            if (orderEntity.getOrOrderClassifyId() == 1) {
                //2.获取订单涉及的对应商品集合
                CompletableFuture<List<OrderCommodityEntity>> orderCommodityList = CompletableFuture.supplyAsync(() -> {
                    return orderCommodityService.list(new QueryWrapper<OrderCommodityEntity>().eq("orc_order_sn", orderEntity.getOrOrderSn()));
                }, executor);
                //2.1.远程 获取商品信息
                CompletableFuture<List<CommodityTo>> commodityTos1 = orderCommodityList.thenApplyAsync((ret) -> {
                    List<Long> collect = ret.stream().map(ite -> {
                        return ite.getOrcCoId();
                    }).collect(Collectors.toList());
                    R r = productFeign.getCommodityList(collect);
                    List<CommodityTo> commodityTos = (List<CommodityTo>) r.get("commodityTos");
                    return commodityTos;
                }, executor);

                //4.远程获取订单店铺信息
                CompletableFuture<Object> businessTo1 = CompletableFuture.supplyAsync(() -> {
                    R r = productFeign.getBusiness(orderEntity.getOrBuId());
                    return r.get("businessTo");
                }, executor);

                OrderClassifyEntity orderClassifyEntity = orderClassifyThread.get();
                List<OrderCommodityEntity> orderCommodityEntities = orderCommodityList.get();
                List<CommodityTo> commodityTos = commodityTos1.get();
                OrderEarthEntity orderEarthEntity = orderEarth.get();
                String shopAddress = (String) businessTo1.get();
                BusinessTo businessTo = JSON.parseObject(shopAddress, BusinessTo.class);

                //计算商品总价
                BigDecimal bigDecimal = new BigDecimal("0");
                for (OrderCommodityEntity orderCommodityEntity : orderCommodityEntities) {
                    BigDecimal multiply = orderCommodityEntity.getOrcCommodityPrice().multiply(new BigDecimal(orderCommodityEntity.getOrcCommodityNum()));
                    bigDecimal = bigDecimal.add(multiply);
                }
                //佣金
                bigDecimal = orderEntity.getOrOrderTotalPrice().subtract(bigDecimal);
                orderDataAllVo = new OrderDataAllVo(bigDecimal, orderEntity, orderClassifyEntity, orderCommodityEntities, commodityTos, orderEarthEntity, businessTo, null);

            } else if (orderEntity.getOrOrderClassifyId() == 0) {
                //查询 OrderReleaseinfoController

                OrderReleaseinfoEntity orderReleaseinfo = orderReleaseinfoService.getOne(new QueryWrapper<OrderReleaseinfoEntity>().eq("oor_order_sn", orderEntity.getOrOrderSn()));

                OrderClassifyEntity orderClassifyEntity = orderClassifyThread.get();
                OrderEarthEntity orderEarthEntity = orderEarth.get();
                //帮领
                orderDataAllVo = new OrderDataAllVo(null, orderEntity, orderClassifyEntity, null, null, orderEarthEntity, null, orderReleaseinfo);
            }
            return orderDataAllVo;
        }

        return null;
    }

}